home *** CD-ROM | disk | FTP | other *** search
/ Programming Microsoft Visual Basic .NET / Programming Microsoft Visual Basic .NET (Microsoft Press)(X08-78517)(2002).bin / setup / vbnet / 21 adonet disconnected / adonetdisconnected / dataadapter.vb < prev    next >
Encoding:
Text File  |  2002-03-16  |  18.4 KB  |  457 lines

  1. Imports System.Data
  2. Imports System.Data.OleDb
  3. Imports System.Data.SqlClient
  4.  
  5. Public Class DataAdapter
  6.     Inherits System.Windows.Forms.Form
  7.  
  8. #Region " Windows Form Designer generated code "
  9.  
  10.     Public Sub New()
  11.         MyBase.New()
  12.  
  13.         'This call is required by the Windows Form Designer.
  14.         InitializeComponent()
  15.  
  16.         'Add any initialization after the InitializeComponent() call
  17.  
  18.     End Sub
  19.  
  20.     'Form overrides dispose to clean up the component list.
  21.     Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean)
  22.         If disposing Then
  23.             If Not (components Is Nothing) Then
  24.                 components.Dispose()
  25.             End If
  26.         End If
  27.         MyBase.Dispose(disposing)
  28.     End Sub
  29.     Friend WithEvents DataGrid1 As System.Windows.Forms.DataGrid
  30.     Friend WithEvents btnReadData As System.Windows.Forms.Button
  31.     Friend WithEvents btnTableMappings As System.Windows.Forms.Button
  32.     Friend WithEvents btnFillSchema As System.Windows.Forms.Button
  33.     Friend WithEvents btnReadMultiple As System.Windows.Forms.Button
  34.     Friend WithEvents btnUpdate As System.Windows.Forms.Button
  35.     Friend WithEvents btnCustomCommands As System.Windows.Forms.Button
  36.  
  37.     'Required by the Windows Form Designer
  38.     Private components As System.ComponentModel.Container
  39.  
  40.     'NOTE: The following procedure is required by the Windows Form Designer
  41.     'It can be modified using the Windows Form Designer.  
  42.     'Do not modify it using the code editor.
  43.     <System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()
  44.         Me.DataGrid1 = New System.Windows.Forms.DataGrid()
  45.         Me.btnReadData = New System.Windows.Forms.Button()
  46.         Me.btnReadMultiple = New System.Windows.Forms.Button()
  47.         Me.btnTableMappings = New System.Windows.Forms.Button()
  48.         Me.btnUpdate = New System.Windows.Forms.Button()
  49.         Me.btnFillSchema = New System.Windows.Forms.Button()
  50.         Me.btnCustomCommands = New System.Windows.Forms.Button()
  51.         CType(Me.DataGrid1, System.ComponentModel.ISupportInitialize).BeginInit()
  52.         Me.SuspendLayout()
  53.         '
  54.         'DataGrid1
  55.         '
  56.         Me.DataGrid1.Anchor = (((System.Windows.Forms.AnchorStyles.Top Or System.Windows.Forms.AnchorStyles.Bottom) _
  57.                     Or System.Windows.Forms.AnchorStyles.Left) _
  58.                     Or System.Windows.Forms.AnchorStyles.Right)
  59.         Me.DataGrid1.DataMember = ""
  60.         Me.DataGrid1.HeaderForeColor = System.Drawing.SystemColors.ControlText
  61.         Me.DataGrid1.Location = New System.Drawing.Point(120, 16)
  62.         Me.DataGrid1.Name = "DataGrid1"
  63.         Me.DataGrid1.Size = New System.Drawing.Size(544, 280)
  64.         Me.DataGrid1.TabIndex = 0
  65.         '
  66.         'btnReadData
  67.         '
  68.         Me.btnReadData.Location = New System.Drawing.Point(8, 16)
  69.         Me.btnReadData.Name = "btnReadData"
  70.         Me.btnReadData.Size = New System.Drawing.Size(104, 40)
  71.         Me.btnReadData.TabIndex = 1
  72.         Me.btnReadData.Text = "Read data"
  73.         '
  74.         'btnReadMultiple
  75.         '
  76.         Me.btnReadMultiple.Location = New System.Drawing.Point(8, 64)
  77.         Me.btnReadMultiple.Name = "btnReadMultiple"
  78.         Me.btnReadMultiple.Size = New System.Drawing.Size(104, 40)
  79.         Me.btnReadMultiple.TabIndex = 1
  80.         Me.btnReadMultiple.Text = "Read three tables"
  81.         '
  82.         'btnTableMappings
  83.         '
  84.         Me.btnTableMappings.Location = New System.Drawing.Point(8, 112)
  85.         Me.btnTableMappings.Name = "btnTableMappings"
  86.         Me.btnTableMappings.Size = New System.Drawing.Size(104, 40)
  87.         Me.btnTableMappings.TabIndex = 1
  88.         Me.btnTableMappings.Text = "Table Mappings"
  89.         '
  90.         'btnUpdate
  91.         '
  92.         Me.btnUpdate.Location = New System.Drawing.Point(8, 208)
  93.         Me.btnUpdate.Name = "btnUpdate"
  94.         Me.btnUpdate.Size = New System.Drawing.Size(104, 40)
  95.         Me.btnUpdate.TabIndex = 1
  96.         Me.btnUpdate.Text = "Update data"
  97.         '
  98.         'btnFillSchema
  99.         '
  100.         Me.btnFillSchema.Location = New System.Drawing.Point(8, 160)
  101.         Me.btnFillSchema.Name = "btnFillSchema"
  102.         Me.btnFillSchema.Size = New System.Drawing.Size(104, 40)
  103.         Me.btnFillSchema.TabIndex = 1
  104.         Me.btnFillSchema.Text = "FillSchema method"
  105.         '
  106.         'btnCustomCommands
  107.         '
  108.         Me.btnCustomCommands.Location = New System.Drawing.Point(8, 256)
  109.         Me.btnCustomCommands.Name = "btnCustomCommands"
  110.         Me.btnCustomCommands.Size = New System.Drawing.Size(104, 40)
  111.         Me.btnCustomCommands.TabIndex = 1
  112.         Me.btnCustomCommands.Text = "Custom commands"
  113.         '
  114.         'DataAdapter
  115.         '
  116.         Me.AutoScaleBaseSize = New System.Drawing.Size(7, 17)
  117.         Me.ClientSize = New System.Drawing.Size(672, 309)
  118.         Me.Controls.AddRange(New System.Windows.Forms.Control() {Me.btnCustomCommands, Me.btnUpdate, Me.btnReadMultiple, Me.btnFillSchema, Me.btnTableMappings, Me.btnReadData, Me.DataGrid1})
  119.         Me.Font = New System.Drawing.Font("Microsoft Sans Serif", 11.0!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
  120.         Me.Name = "DataAdapter"
  121.         Me.Text = "DataAdapter"
  122.         CType(Me.DataGrid1, System.ComponentModel.ISupportInitialize).EndInit()
  123.         Me.ResumeLayout(False)
  124.  
  125.     End Sub
  126.  
  127. #End Region
  128.  
  129.     ' ensure that only one of these constants is -1
  130. #Const OLEDBBIBLIO = -1
  131. #Const OLEDBPUBS = 0
  132. #Const SQLPUBS = 0
  133.  
  134.     Dim ds As New DataSet()
  135.  
  136.     Private Sub btnReadData_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnReadData.Click
  137.         ' Create a DataAdapter that reads and writes the Publishers table.
  138.         Dim sql As String = "SELECT * FROM Publishers"
  139.  
  140. #If OLEDBBIBLIO Then
  141.             Dim cn As New OleDbConnection(BiblioConnString)
  142.             dim da as New OleDbDataAdapter(sql, cn)
  143. #ElseIf OLEDBPUBS Then
  144.         Dim cn As New OleDbConnection(OledbPubsConnString)
  145.         Dim da As New OleDbDataAdapter(sql, cn)
  146. #ElseIf SQLPUBS Then
  147.             Dim cn As New SqlConnection(SqlPubsConnString)
  148.             dim da as New SqlDataAdapter (sql, cn)
  149. #End If
  150.  
  151. #Const DA_BASED_ON_PARAMETERIZED_COMMAND = False
  152.  
  153. #If DA_BASED_ON_PARAMETERIZED_COMMAND Then
  154.             ' Create a Command object with parameters
  155.             Dim sql As String = "SELECT * FROM Publishers WHERE Name LIKE ?"
  156.             Dim cmd As New OleDbCommand(sql, cn)
  157.             ' Create the parameter with an initial value.
  158.             cmd.Parameters.Add("PubNameLike", "S%")
  159.             ' Create the DataAdapter based on the parameterized command.
  160.             da = New DataAdapter(cmd)
  161.             ' Fill the DataSet with a subset of the Publishers table.
  162.             da.Fill(ds, "Publishers")
  163.  
  164.             cmd.Parameters(0).Value = "M%"
  165. #End If
  166.  
  167.         ' fill the dataset
  168.         da.Fill(ds, "Publishers")
  169.         ' show the result.
  170.         DataGrid1.DataSource = ds.Tables("Publishers")
  171.     End Sub
  172.  
  173.     ' demonstrate how a data adapter can read 3 tables
  174.  
  175.     Private Sub btnReadMultiple_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnReadMultiple.Click
  176.         ' Create a DataAdapter that reads and writes 3 tables.
  177.         Dim sql As String = "SELECT * FROM Publishers;SELECT * FROM Titles;SELECT * FROM Authors"
  178. #If OLEDBBIBLIO Or OLEDBPUBS Then
  179.         Dim cn As New OleDbConnection(OledbPubsConnString)
  180.         Dim da As New OleDbDataAdapter(sql, cn)
  181. #ElseIf SQLPUBS Then
  182.             Dim cn As New SqlConnection(SqlPubsConnString)
  183.             Dim da As New SqlDataAdapter(sql, cn)
  184. #End If
  185.  
  186.         ' Create and Fill the DataSet's Publishers table.
  187.         da.Fill(ds, "Publishers")
  188.  
  189.         ' change the names of 2nd and 3rd table
  190.         ds.Tables(1).TableName = "Titles"
  191.         ds.Tables(2).TableName = "Authors"
  192.         DataGrid1.DataSource = ds.Tables("Titles")
  193.     End Sub
  194.  
  195.     ' demonstrate the TableMappings object
  196.  
  197.     Private Sub btnTableMappings_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnTableMappings.Click
  198.  
  199.         Dim sql As String = "SELECT * FROM Publishers"
  200.  
  201. #If OLEDBBIBLIO Then
  202.         Dim cn As New OleDbConnection(BiblioConnString)
  203.         Dim da As New OleDbDataAdapter(sql, cn)
  204. #ElseIf OLEDBPUBS Then
  205.         Dim cn As New OleDbConnection(OledbPubsConnString)
  206.         Dim da As New OleDbDataAdapter(sql, cn)
  207. #ElseIf SQLPUBS Then
  208.             Dim cn As New SqlConnection(SqlPubsConnString)
  209.             Dim da As New SqlDataAdapter(sql, cn)
  210. #End If
  211.  
  212.         ' Adds an element to the TableMappings collection. 
  213.         ' (Returns a DataTableMapping object.)
  214.         With da.TableMappings.Add("Publishers", "DataPublishers")
  215.             ' Add two element to the ColumnMappings collection.
  216.             .ColumnMappings.Add("pub_id", "ID")
  217.             .ColumnMappings.Add("pub_name", "Name")
  218.         End With
  219.  
  220.         ' The following block of code makes the DataAdapter import only two fields.
  221. #Const IMPORT_ONLY_TWO_FIELDS = False
  222.  
  223. #If IMPORT_ONLY_TWO_FIELDS Then
  224.                 With ds.Tables.Add("DataPublishers")
  225.                     .Columns.Add("ID", GetType(String))
  226.                     .Columns.Add("Name", GetType(String))
  227.                 End With
  228.                 da.MissingSchemaAction = MissingSchemaAction.Ignore
  229. #End If
  230.  
  231.         ' Fill the DataSet with the source Publishers table, using the prepared mappings
  232.         da.Fill(ds, "Publishers")
  233.         DataGrid1.DataSource = ds.Tables("DataPublishers")
  234.     End Sub
  235.  
  236.     ' demonstrate the FillSchema method
  237.  
  238.     Private Sub btnFillSchema_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnFillSchema.Click
  239.         Dim sql As String = "SELECT * FROM Publishers;SELECT * FROM Titles;SELECT * FROM authors"
  240.  
  241. #If OLEDBBIBLIO Or OLEDBPUBS Then
  242.         Dim cn As New OleDbConnection(OledbPubsConnString)
  243.         Dim da As New OleDbDataAdapter(sql, cn)
  244. #ElseIf SQLPUBS Then
  245.             Dim cn As New SqlConnection(SqlPubsConnString)
  246.             Dim da As New SqlDataAdapter(sql, cn)
  247. #End If
  248.  
  249.         With da.TableMappings.Add("Publishers", "DataPublishers")
  250.             ' Add two element to the ColumnMappings collection.
  251.             .ColumnMappings.Add("pub_id", "ID")
  252.             .ColumnMappings.Add("pub_name", "Name")
  253.         End With
  254.         da.FillSchema(ds, SchemaType.Source, "Publishers")
  255.         ' Change the name of the 2nd and 3rd tables.
  256.         ds.Tables(1).TableName = "Titles"
  257.         ds.Tables(2).TableName = "Authors"
  258.  
  259.         DataGrid1.DataSource = ds.Tables("Authors")
  260.     End Sub
  261.  
  262.     ' perform an update
  263.  
  264.     Private Sub btnUpdate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnUpdate.Click
  265.  
  266.         Dim sql As String = "SELECT * FROM Publishers"
  267.  
  268. #If OLEDBBIBLIO Then
  269.         Dim cn As New OleDbConnection(BiblioConnString)
  270.         Dim da As New OleDbDataAdapter(sql, cn)
  271. #ElseIf OLEDBPUBS Then
  272.         Dim cn As New OleDbConnection(OledbPubsConnString)
  273.         Dim da As New OleDbDataAdapter(sql, cn)
  274. #ElseIf SQLPUBS Then
  275.             Dim cn As New SqlConnection(SqlPubsConnString)
  276.             Dim da As New SqlDataAdapter(sql, cn)
  277. #End If
  278.         cn.Open()
  279.         da.Fill(ds, "Publishers")
  280.  
  281.         DataGrid1.DataSource = ds.Tables("Publishers")
  282.  
  283. #If OLEDBBIBLIO Or OLEDBPUBS Then
  284.         Dim cmdBuilder As New OleDbCommandBuilder(da)
  285.         cmdBuilder.QuotePrefix = "["
  286.         cmdBuilder.QuoteSuffix = "]"
  287.         Dim par As OleDbParameter
  288.  
  289. #ElseIf SQLPUBS Then
  290.             Dim cmdBuilder As New SqlCommandBuilder(da)
  291.             Dim par As SqlParameter
  292. #End If
  293.         ' generate the three default commands
  294.         da.DeleteCommand = cmdBuilder.GetDeleteCommand
  295.         da.InsertCommand = cmdBuilder.GetInsertCommand
  296.         da.UpdateCommand = cmdBuilder.GetUpdateCommand
  297.  
  298.         ' Display info on auto-generated commands
  299.         Debug.WriteLine(da.InsertCommand.CommandText)
  300.         Debug.WriteLine(da.UpdateCommand.CommandText)
  301.         Debug.WriteLine(da.DeleteCommand.CommandText)
  302.         For Each par In da.UpdateCommand.Parameters
  303.             Debug.WriteLine(par.ParameterName & " => " & par.SourceColumn & "(" & par.SourceVersion.ToString & ")")
  304.         Next
  305.  
  306. #If OLEDBBIBLIO Then
  307.         With ds.Tables("Publishers")
  308.             ' Modify the first record
  309.             .Rows(0)("Name") = .Rows(0)("Name").ToString & " ***"
  310.  
  311.             ' Add a new record
  312.             Dim dr As DataRow = .NewRow
  313.             dr("Name") = "VB2TheMax"
  314.             .Rows.Add(dr)
  315.         End With
  316. #Else
  317.         With ds.Tables("Publishers")
  318.             ' Modify the first record
  319.             .Rows(0)("pub_name") = .Rows(0)("pub_name").ToString & " ***"
  320.             ' Add a new record
  321.             Dim dr As DataRow = .NewRow
  322.             dr("pub_id") = "9988"
  323.             dr("pub_name") = "Vb2TheMax"
  324.             dr("city") = "Bari"
  325.             dr("country") = "Italy"
  326.             .Rows.Add(dr)
  327.         End With
  328. #End If
  329.  
  330.         ' Send changes them to the database.
  331.         da.Update(ds, "Publishers")
  332.     End Sub
  333.  
  334.     ' demonstrates using custom update commands
  335.  
  336.     Private Sub btnCustomCommands_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCustomCommands.Click
  337.         ' This requires that you've added a field named LastUpdate of type timestamp
  338.         ' to the Authors table.
  339.         Dim sql As String = "SELECT au_id,au_fname,au_lname,lastupdate FROM Authors"
  340.  
  341.         ' This sample only works for SQL server
  342. #If OLEDBBIBLIO Or OLEDBPUBS Then
  343.         Dim cn As New OleDbConnection(OledbPubsConnString)
  344.         Dim da As New OleDbDataAdapter(sql, cn)
  345. #ElseIf SQLPUBS Then
  346.             Dim cn As New SqlConnection(SqlPubsConnString)
  347.             Dim da As New SqlDataAdapter(sql, cn)
  348. #End If
  349.         ' No need to explicitly open and close the connection.
  350.         'cn.Open()
  351.  
  352.         da.Fill(ds, "Authors")
  353.         DataGrid1.DataSource = ds.Tables("Authors")
  354.  
  355.         ' Generate custom commands
  356. #If OLEDBBIBLIO Or OLEDBPUBS Then
  357.         Dim cmdBuilder As New OleDbCommandBuilder(da)
  358. #Else
  359.             Dim cmdBuilder As New SqlCommandBuilder(da)
  360. #End If
  361.         da.InsertCommand = cmdBuilder.GetInsertCommand
  362.         da.UpdateCommand = cmdBuilder.GetUpdateCommand
  363.         da.DeleteCommand = cmdBuilder.GetDeleteCommand
  364.  
  365. #Const GENERATE_CUSTOM_DELETE_COMMAND = False
  366. #Const GENERATE_CUSTOM_DELETE_WITH_TIMESTAMP = False
  367.  
  368.  
  369. #If GENERATE_CUSTOM_DELETE_COMMAND Then
  370.             ' create a custom delete command
  371.             Dim cmdDelete As New OleDbCommand("DELETE FROM Authors WHERE Au_ID = ?", cn)
  372.             With cmdDelete.Parameters.Add("@p1", GetType(Integer))
  373.                 .SourceColumn = "Au_id"
  374.                 .SourceVersion = DataRowVersion.Original
  375.             End With
  376.             da.DeleteCommand = cmdDelete
  377.  
  378.             ' Create a custom update command.
  379.             Dim cmdUpdate As New OleDbCommand("UPDATE Authors SET Author = ? , [Year Born] = ? WHERE Au_ID = ?", cn)
  380.             ' Add arguments for the SET clause, that use the current field value.
  381.             With cmdUpdate.Parameters.Add("@p1", GetType(String))
  382.                 .SourceColumn = "Authors"
  383.                 .SourceVersion = DataRowVersion.Current
  384.             End With
  385.             With cmdUpdate.Parameters.Add("@p2", GetType(Integer))
  386.                 .SourceColumn = "Year Born"
  387.                 .SourceVersion = DataRowVersion.Current
  388.             End With
  389.             ' Add the only argument in the WHERE clase, that uses the original field value.
  390.             With cmdUpdate.Parameters.Add("@p3", GetType(Integer))
  391.                 .SourceColumn = "Au_id"
  392.                 .SourceVersion = DataRowVersion.Original
  393.             End With
  394.             da.UpdateCommand = cmdUpdate
  395.  
  396. #ElseIf GENERATE_CUSTOM_DELETE_WITH_TIMESTAMP Then
  397.             ' Create a custom delete command that uses the timestamp field.
  398.         ' IMPORTANT: this assumes that you've expanded the Authors table
  399.         ' with a LastUpdate field of type TimeStamp
  400.  
  401.             Dim cmdDelete As New OleDbCommand("DELETE FROM Authors WHERE Au_ID = ? And LastUpdate=?", cn)
  402.             With cmdDelete.Parameters.Add("@p1", GetType(Integer))
  403.                 .SourceColumn = "Au_id"
  404.                 .SourceVersion = DataRowVersion.Original
  405.             End With
  406.             ' Timestamp values are saved as arrays of Byte.
  407.             With cmdDelete.Parameters.Add("@p2", GetType(Byte()))
  408.                 .SourceColumn = "LastUpdate"
  409.                 .SourceVersion = DataRowVersion.Original
  410.             End With
  411.             da.DeleteCommand = cmdDelete
  412.  
  413.             ' Create a custom update command.
  414.             Dim cmdUpdate As New OleDbCommand("UPDATE Authors SET au_fname = ? , au_lname = ? WHERE au_id = ? AND LastUpdate=?", cn)
  415.             ' Add arguments for the SET clause, that use the current field value.
  416.             With cmdUpdate.Parameters.Add("@p1", GetType(String))
  417.                 .SourceColumn = "au_fname"
  418.                 .SourceVersion = DataRowVersion.Current
  419.             End With
  420.             With cmdUpdate.Parameters.Add("@p2", GetType(Integer))
  421.                 .SourceColumn = "au_lname"
  422.                 .SourceVersion = DataRowVersion.Current
  423.             End With
  424.             ' Add the arguments in the WHERE clase, that uses the original field value.
  425.             With cmdUpdate.Parameters.Add("@p3", GetType(Integer))
  426.                 .SourceColumn = "Au_id"
  427.                 .SourceVersion = DataRowVersion.Original
  428.             End With
  429.             ' Timestamp values are saved as arrays of Byte.
  430.             With cmdUpdate.Parameters.Add("@p4", GetType(Byte()))
  431.                 .SourceColumn = "LastUpdate"
  432.                 .SourceVersion = DataRowVersion.Original
  433.             End With
  434.             da.UpdateCommand = cmdUpdate
  435. #End If
  436.  
  437.         ' delete some rows
  438.         ' NOTE: these statement are commented because they would
  439.         ' raise a referential integrity error
  440.         'ds.Tables("Authors").Rows(0).Delete()
  441.         'ds.Tables("Authors").Rows(1).Delete()
  442.         'ds.Tables("Authors").Rows(2).Delete()
  443.  
  444.         ' Change some values.
  445.         With ds.Tables("Authors")
  446.             .Rows(0)("au_fname") = .Rows(0)("au_fname").ToString & " New"
  447.             .Rows(1)("au_fname") = .Rows(1)("au_fname").ToString & " New"
  448.         End With
  449.  
  450.         ' Send changes them to the database.
  451.         ' Again, no need to explicitly open and close the connection.
  452.         da.Update(ds, "Authors")
  453.  
  454.     End Sub
  455.  
  456. End Class
  457.